import os

from PySide6.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QLabel, QLineEdit, QPushButton, QSizePolicy, QStyle, \
    QStyleOption,QApplication,QListWidget,QListWidgetItem,QSpinBox,QFileDialog
from PySide6.QtCore import Qt,Signal,QSize
from PySide6.QtGui import QFont, QPainter, QPixmap

from core.setting import SHAREURL,BASEPATH

with open('setting','r',encoding='utf-8') as data:
    lines = data.readlines()
    MODSAVEPATH = eval(lines[1].split('=')[1].replace('\n', ''))
    IMGLOADTHREADCOUNT = eval(lines[2].split('=')[1].replace('\n', ''))
    DOWNLOADTHREADCOUNT = eval(lines[3].split('=')[1].replace('\n', ''))

class NoticeBase(QWidget):
    def __init__(self,width:int,height:int,title:str):
        super().__init__()
        self._width = width
        self._height = height
        self._press = False

        self.confirmButton = MyPushButton('确认')
        self.cancelButton = MyPushButton('取消')
        self.titleText = QLabel(title)
        self.buttonLayout = QHBoxLayout()
        self.vlayout = QVBoxLayout(self)
        self.init()

    def init(self):
        self.setObjectName('NoticeBase')
        self.setFixedSize(self._width,self._height)
        self.setWindowFlag(Qt.WindowType.SubWindow | Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_TranslucentBackground)  # 设置透明(无法圆角原因)
        self.setAttribute(Qt.WA_StyledBackground, True)
        self.setStyleSheet(
            """
            QLineEdit{
                        color: white;
                        padding-left: 12px;
                        padding-right: 40px;
                        border: 2px solid gray;
                        border-radius: 20px;
                        background-color: #282c35;
                                }
            QPushButton{
                        background:rgba(0,0,0,0);
                                }
            QListWidget{
                        background-color:#282c35;
                        border-radius:8px;
            }
            #NoticeBase{
                        background-color: #1a1c1e;
                        border-radius: 20px;
            }
            #NoticeBase>QPushButton{
                        color:#ffffff;
                        background-color:#1b6ef3ff;
                        border-radius:16px;
            }
            #NoticeBase>QPushButton:hover{
                        color:#ffffff;
                        background-color:#a8c7faff;
            }
            #NoticeBase>QLabel{
                        color:white;
            }              
            QScrollArea{
                        border: 0px solid;
                        border-right-width: 1px;
                        border-right-color: #dcdbdc;
                        background-color: #f5f5f7;
            }
            QScrollBar:vertical {
                        border: none;
                        background: rgb(69,74,77);
                        width: 10px;
                        margin: 0px 0 0px 0;
            }
            QScrollBar::handle:vertical {
                        background: Gainsboro;
                        min-height: 20px;
                        border-radius: 5px;
                        border: none;
            }
            QScrollBar::handle:vertical:hover{
                        background-color:rgb(159,221,253);
            }
            QScrollBar::handle:vertical:pressed{
                        background-color:rgb(61, 168, 255);
            }
            QScrollBar::add-line:vertical {
                        border: 0px solid grey;
                        background: #32CC99;
                        height: 0px;
                        subcontrol-position: bottom;
                        subcontrol-origin: margin;
            }
            QScrollBar::sub-line:vertical {
                        border: 0px solid grey;
                        background: #32CC99;
                        height: 0px;
                        subcontrol-position: top;
                        subcontrol-origin: margin;
            }
            QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
                        background: none;
                        width: 0px;
                        height: 0px;
            }
            """
        )

        self.titleText.setFont(QFont('微软雅黑', 16))
        self.titleText.setWordWrap(True)
        self.titleText.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) # 设置固定大小策略 下方adjustSize()方有效
        self.titleText.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.titleText.adjustSize()

        self.confirmButton.setFont(QFont('微软雅黑', 14))
        self.cancelButton.setFont(QFont('微软雅黑', 14))
        self.confirmButton.setFixedSize(75,35)
        self.cancelButton.setFixedSize(75,35)

        self.vlayout.addWidget(self.titleText,Qt.AlignmentFlag.AlignLeft)
        self.vlayout.setSpacing(5)

    def confirmEvent(self):
        self.hide()

    def cancelEvent(self):
        self.hide()

    def setBaseButton(self):
        self.confirmButton.clicked.connect(self.confirmEvent)
        self.cancelButton.clicked.connect(self.cancelEvent)
        self.buttonLayout.addStretch(1)
        self.buttonLayout.addWidget(self.confirmButton, alignment=Qt.AlignmentFlag.AlignRight)
        self.buttonLayout.addWidget(self.cancelButton, alignment=Qt.AlignmentFlag.AlignRight)
        self.buttonLayout.setSpacing(10)
        self.buttonLayout.setContentsMargins(0, 0, 15, 8)
        self.vlayout.addLayout(self.buttonLayout)

    def setContents(self,widget=None,layout=None):
        if layout:
            self.vlayout.addLayout(layout)
        if widget:
            self.vlayout.addWidget(widget)
        self.setBaseButton()

    def mousePressEvent(self, event):
        super().mousePressEvent(event)
        if event.button() == Qt.MouseButton.LeftButton and 0 < event.pos().y() < 50:
            self._press = True
            self.mouseStartPos = event.globalPos()
            self.windowTopLeftPos = self.frameGeometry().topLeft() # 由于它是一个子窗口无父类，本身坐标系等同于窗口坐标

    def mouseMoveEvent(self, event):
        super().mouseMoveEvent(event)
        if self._press:
            distance = event.globalPos() - self.mouseStartPos
            self.move(self.windowTopLeftPos + distance)

    def mouseReleaseEvent(self, event):
        super().mouseReleaseEvent(event)
        if self._press:
            self._press = False

    def paintEvent(self, event):
        opt = QStyleOption()
        opt.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PrimitiveElement.PE_Widget,opt,p,self)

        super().paintEvent(event)

class setShortcut(NoticeBase):
    setShortcutCell = Signal(str,str)
    def __init__(self,title:str='添加快捷站点',width:int=450,height:int=250):
        super().__init__(width,height,title)
        self._width = width

        self.inputName = QLineEdit()
        self.inputUrl = QLineEdit()

        self.initSetup()

    def initSetup(self):
        layout = QVBoxLayout()

        name = QLabel('名称：')
        url = QLabel('网址：')

        name.adjustSize()
        url.adjustSize()

        tipTextFont = QFont('微软雅黑',13)

        name.setFont(tipTextFont)
        url.setFont(tipTextFont)

        self.inputName.setFixedSize(400,30)
        self.inputUrl.setFixedSize(400,30)

        layout.addWidget(name,alignment=Qt.AlignmentFlag.AlignLeft)
        layout.addWidget(self.inputName,alignment=Qt.AlignmentFlag.AlignHCenter)
        layout.addWidget(url,alignment=Qt.AlignmentFlag.AlignLeft)
        layout.addWidget(self.inputUrl,alignment=Qt.AlignmentFlag.AlignHCenter)

        layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        layout.setSpacing(10)
        layout.setContentsMargins(3,0,0,0)

        self.setContents(layout=layout)

    def setInput(self,name:str,url:str):
        self.inputName.setText(name)
        self.inputUrl.setText(url)

    def confirmEvent(self):
        nameText = self.inputName.text()
        urlText = self.inputUrl.text()
        # 验证网址地址
        if not ('http://' in urlText or 'https://' in urlText):
            pass

        # 更新快捷面板界面
        self.setShortcutCell.emit(nameText,urlText)

        super().confirmEvent()

    def cancelEvent(self):
        super().cancelEvent()
        self.inputName.clear()
        self.inputUrl.clear()

class sharePage(NoticeBase):
    def __init__(self, title: str = '--> 分享我 <--', width: int = 350, height: int = 450):
        super().__init__(width, height, title)
        self._width = width
        self._height = height

        self.url = SHAREURL + '\n密码:jx44'
        self.urlPixmap = QPixmap('./img/AppShareCode.png')
        self.initSetup()

    def initSetup(self):
        # 二维码 链接 参考蓝奏云分享界面
        self.vlayout.setAlignment(self.titleText,Qt.AlignmentFlag.AlignHCenter)
        self.confirmButton.setText('复制')

        layout = QVBoxLayout()
        nameFont = QFont('微软雅黑',13)

        name_1 = QLabel('链接：')
        name_2 = QLabel('二维码：')
        name_1.setFont(nameFont)
        name_2.setFont(nameFont)

        url = QLabel(self.url)
        url.setFont(QFont('微软雅黑',11))
        url.setIndent(25)

        img = QLabel()
        img.setPixmap(self.urlPixmap)
        img.setAlignment(Qt.AlignmentFlag.AlignHCenter)

        layout.addWidget(name_1)
        layout.addWidget(url)
        layout.addWidget(name_2)
        layout.addWidget(img)

        layout.setSpacing(20)
        layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.setContents(layout=layout)

    def setBaseButton(self):
        self.confirmButton.clicked.connect(self.confirmEvent)
        self.buttonLayout.addWidget(self.confirmButton, alignment=Qt.AlignmentFlag.AlignHCenter)
        self.vlayout.addLayout(self.buttonLayout)

    def confirmEvent(self):
        super().confirmEvent()
        clip = QApplication.clipboard()
        if self.confirmButton._pressButton == Qt.MouseButton.LeftButton:
            clip.setText(self.url)
        else:
            clip.setPixmap(QPixmap('./img/AppShare.png'))

class appSetupPage(NoticeBase):
    restart = Signal()
    def __init__(self, title: str = '设置', width: int = 450, height: int = 350):
        super().__init__(width, height, title)
        self._width = width

        self.imgDTCInput = QSpinBox()
        self.modDTCInput = QSpinBox()
        self.saveDir = QLineEdit()
        self.fileSelect = QPushButton()

        self.bind()
        self.initSetup()

    def bind(self):
        self.fileSelect.clicked.connect(self.selctSavePath)
        self.confirmButton.clicked.connect(self.updateSetup)

    def initSetup(self):
        global MODSAVEPATH
        vlayout = QVBoxLayout()
        vlayout.setSpacing(10)

        self.imgDTCInput.setRange(1,500)
        self.modDTCInput.setRange(1,500)
        self.imgDTCInput.setValue(IMGLOADTHREADCOUNT)
        self.modDTCInput.setValue(DOWNLOADTHREADCOUNT)
        self.imgDTCInput.setFixedHeight(25)
        self.modDTCInput.setFixedHeight(25)
        self.fileSelect.setIconSize(QSize(24,24))
        self.fileSelect.setIcon(QPixmap('./img/open.png'))

        if MODSAVEPATH.startswith('/'):
            self.saveDir.setText(BASEPATH+os.path.normpath(MODSAVEPATH))
            MODSAVEPATH = BASEPATH+os.path.normpath(MODSAVEPATH)
        else:
            self.saveDir.setText(os.path.normpath(MODSAVEPATH))

        TipFont = QFont('微软雅黑',15)

        saveTip = QLabel('保存目录：')
        imgTip = QLabel('图片载入线程数：')
        modTip = QLabel('模组下载线程数：')

        saveTip.setFont(TipFont)
        imgTip.setFont(TipFont)
        modTip.setFont(TipFont)

        self.vLayoutAddWidget(widgets=(saveTip,self.saveDir,self.fileSelect),vlayout=vlayout)
        self.vLayoutAddWidget(widgets=(imgTip,self.imgDTCInput),vlayout=vlayout)
        self.vLayoutAddWidget(widgets=(modTip,self.modDTCInput),vlayout=vlayout)

        self.setContents(layout=vlayout)

    def vLayoutAddWidget(self,widgets:tuple,vlayout):
        hlayout = QHBoxLayout()
        for widget in widgets:
            hlayout.addWidget(widget)

        hlayout.setSpacing(5)
        vlayout.addLayout(hlayout)

    def updateSetup(self):
        self.updateSavePath()
        self.updateThreadCount()
        self.restart.emit()

    def selctSavePath(self):
        path = QFileDialog.getExistingDirectory(self, '选择模组保存的路径','/')
        self.saveDir.setText(os.path.normpath(path))

    def updateSavePath(self):
        if MODSAVEPATH == self.saveDir.text():
            return

        with open('setting', 'r+', encoding='utf-8') as data:
            t = data.read()
            startIndex = t.find('MODSAVEPATH')
            endIndex = t.find('\n', startIndex)

            text = t[startIndex:endIndex].split('=')
            value = self.saveDir.text().replace('\\','/')
            text[1] = f"r'{value}'"
            text = '= '.join(text)
            newT = t.replace(t[startIndex:endIndex],text)

            data.seek(0)
            data.truncate()
            data.write(newT)

    def updateThreadCount(self):
        updateDict = {}

        if IMGLOADTHREADCOUNT != self.imgDTCInput.value():
            updateDict['IMGLOADTHREADCOUNT'] = self.imgDTCInput.value()
        if DOWNLOADTHREADCOUNT != self.modDTCInput.value():
            updateDict['DOWNLOADTHREADCOUNT'] = self.modDTCInput.value()

        for key,value in updateDict.items():
            with open('setting', 'r+', encoding='utf-8') as data:
                t = data.read()
                startIndex = t.find(key)
                endIndex = t.find('\n', startIndex)

                text = t[startIndex:endIndex].split('=')
                text[1] = f'{value}'
                text = '= '.join(text)
                newT = t.replace(t[startIndex:endIndex],text)

                data.seek(0)
                data.truncate()
                data.write(newT)

class historysPage(NoticeBase):
    jumpUrl = Signal(str)
    def __init__(self, title: str = '历史', width: int = 350, height: int = 350):
        super().__init__(width, height, title)
        self._width = width
        self._height = height
        self.historyDict = {}

        self.historyList = QListWidget()
        self.initSetup()

    def initSetup(self):
        self.historyList.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.historyList.setTextElideMode(Qt.TextElideMode.ElideMiddle) # 设置文本中间省略
        self.confirmButton.setText('跳转')

        self.updateHistory()
        self.setContents(widget=self.historyList)

    def updateHistory(self):
        self.historyList.clear()
        with open('../log/historyLog.txt','r',encoding='utf-8') as data:
            historyLines = data.readlines()
            if historyLines:
                for index,line in enumerate(historyLines):
                    name,value = line.strip().split(':',1)

                    if name == '重命名':
                        item = QListWidgetItem(value)
                    else:
                        item = QListWidgetItem(name)

                    item.setFont(QFont('微软雅黑',14))

                    self.historyList.addItem(item)
                    self.historyDict[index] = value

            else:
                item = QListWidgetItem('无记录')
                item.setFont(QFont('微软雅黑',15))
                self.historyList.addItem(item)

    def confirmEvent(self):
        super().confirmEvent()
        items = self.historyList.selectedIndexes()
        if items:
            item = items[0].row()
            url = self.historyDict.get(item,None)
            if url:
                self.jumpUrl.emit(url)

class MyPushButton(QPushButton):
    def __init__(self,parent=None):
        super().__init__(parent)
        self._pressButton = None

    def mousePressEvent(self, e):
        self._pressButton = e.button()
        if self._pressButton == Qt.MouseButton.LeftButton:
            super().mousePressEvent(e)
        else:
            self.click()